package com.farm.iproject.service.impl;

import com.farm.iproject.domain.Wordex;
import com.farm.core.time.TimeTool;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import com.farm.iproject.dao.WordexDaoInter;
import com.farm.iproject.service.WordexServiceInter;
import com.farm.parameter.service.impl.XmlConfigFileService;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wltea.analyzer.cfg.Configuration;
import org.wltea.analyzer.cfg.DefaultConfig;
import org.wltea.analyzer.dic.Dictionary;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：扩展字典服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class WordexServiceImpl implements WordexServiceInter {
	@Resource
	private WordexDaoInter wordexDaoImpl;

	private static final Logger log = Logger.getLogger(WordexServiceImpl.class);

	@Override
	@Transactional
	public Wordex insertWordexEntity(Wordex entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setPstate("1");
		return wordexDaoImpl.insertEntity(entity);
	}

	@Override
	@Transactional
	public Wordex editWordexEntity(Wordex entity, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		Wordex entity2 = wordexDaoImpl.getEntity(entity.getId());
		// entity2.setEuser(user.getId());
		// entity2.setEusername(user.getName());
		// entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setType(entity.getType());
		entity2.setWord(entity.getWord());
		entity2.setPstate(entity.getPstate());
		entity2.setPcontent(entity.getPcontent());
		entity2.setCtime(entity.getCtime());
		entity2.setCuser(entity.getCuser());
		entity2.setId(entity.getId());
		wordexDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteWordexEntity(String id, LoginUser user) {
		wordexDaoImpl.deleteEntity(wordexDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public Wordex getWordexEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return wordexDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createWordexSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "WSCH_S_WORDEX", "ID,TYPE,WORD,PSTATE,PCONTENT,CTIME,CUSER");
		return dbQuery;
	}

	@Override
	@Transactional
	public void addWordToFile(String id) {
		// TODO 暂时未实现
	}

	private File getDicFile(String type) {
		File file = null;
		if (type.equals("1")) {
			URL url = WordexServiceImpl.class.getClassLoader().getResource("dics/lucene-ext.dic");
			file = new File(url.getFile());
		}
		if (type.equals("2")) {
			URL url = WordexServiceImpl.class.getClassLoader().getResource("dics/lucene-stop.dic");
			file = new File(url.getFile());
		}
		if (file != null) {
			log.info(file.getPath());
		}
		return file;
	}

	@Override
	@Transactional
	public void reLoadToFile() {
		reLoadToFile("1");
		reLoadToFile("2");
	}

	private void reLoadToFile(String type) {
		File file = getDicFile(type);
		List<Wordex> words = wordexDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("TYPE", type, "=")).toList());
		// --------------
		FileOutputStream writerStream = null;
		BufferedWriter out = null;
		Set<String> wordSet = new HashSet<>();
		try {
			writerStream = new FileOutputStream(file);
			out = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
			StringBuffer text = new StringBuffer();
			for (Wordex word : words) {
				text.append(word.getWord() + "\n");
				wordSet.add(word.getWord());
			}
			out.write(text.toString());
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				writerStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		addWordToIK(wordSet, type);
	}

	/**
	 * 立即加载字典
	 * 
	 * @param words
	 * @param type
	 */
	private void addWordToIK(Set<String> words, String type) {
		Configuration cfg = DefaultConfig.getInstance();
		Dictionary.initial(cfg);
		Dictionary dic = Dictionary.getSingleton();
		if (type.equals(type)) {
			dic.addWords(words);
		} else {
			dic.disableWords(words);
		}
	}
}
